package com.yanqu.road.server.cmd.base;

import com.yanqu.road.server.command.Command;
import com.yanqu.road.message.YanQuMessage;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;

public abstract class AbstractServerCommand implements Command {

    protected static Logger log = LogManager.getLogger(AbstractServerCommand.class.getName());

    private static Logger cmdLogger = LogManager.getLogger("COMMAND_TIME");
    /**
     * 结果值
     */
    protected int ret = 0;

    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        Date start = new Date();
        try {
            if (parseData(packet)) {
                execute(packet);
                sendData(packet);
            }
        } catch (Exception e) {
            log.error("ServerCmd error, code: {}", packet.getCode(), e);
        } finally {
            Date endDate = new Date();
            long costTime = endDate.getTime() - start.getTime();
            if (costTime > 50) {
                cmdLogger.debug("exec server cmd cost time {} Millis, protocol Num:{} class:{}  ", costTime,
                        packet.getCode(), getClass().getSimpleName());
            }
        }
    }

    public abstract boolean parseData(YanQuMessage packet) throws Exception;

    public abstract void execute(YanQuMessage packet) throws Exception;

    public abstract void sendData(YanQuMessage packet) throws Exception;
}
